# -*- coding: utf-8 -*-
from flask import  Blueprint, render_template, request,session,flash
from flask_login import login_required,current_user
from collections import namedtuple
import json,pymongo
import random
from app import mongo,cache
import logging
from models import ReCommand
from datetime import datetime
avbd_app = Blueprint('avbd_app', __name__, template_folder='templates')

log = logging.getLogger(__name__)
@avbd_app.route("/act_data")
@login_required
def get_act_data():
	columns = ['Name', 'Cup', 'Bust', 'Age','Height','Birthday','Hometown','Hobby']
	index_column = "_id"
	collection = "act"
	name = 'all'
	results = DataTablesServer(request, columns, index_column, collection,'',name).act_result()
	return json.dumps(results)

@avbd_app.route('/type')
@login_required
@cache.cached(timeout=None)
def type_list():
	data = mongo.db.mov.find()
	type = {x for i in data for x in i['type']}
	type = ["<a href=/type/%s>%s</a>" %(x,x) for x in type]
	result = [type[i:i+15] for i in xrange(0,len(type),15)]
	return render_template('type.html',type=result)



@avbd_app.route('/')
@login_required
def index():
	data = mongo.db.act.count()
	return render_template('index.html',data=data)

@avbd_app.route('/search',methods=['POST'])
@login_required
def search():
	search_key = request.form['data']
	data = mongo.db.mov.find({"$text": {"$search": search_key}})
	return render_template('search.html',data=data)


@avbd_app.route('/lucky')
@login_required
def lucky():
	reDate =  datetime.now().date()
	reDateStr = datetime.strftime(reDate,"%Y-%m-%d")
	result = None
	try:
		if session['reDate'] == reDateStr:
			movDate = mongo.db.re_command.find({'email':current_user.email})
			result = [i for i in movDate]
		else:
			mongo.db.re_command.remove({'email': current_user.email})
			session['reDate'] = reDateStr
			count = mongo.db.mov.count()
			result = list()
			for _ in xrange(3):
				x = mongo.db.mov.find()[random.randrange(count)]
				reObject = ReCommand(code=x['code'],
									 postTime=x['postTime'],
									 publisher=x['publisher'],
									 type=x['type'],
									 actress=x['actress'],
									 director=x['director'],
									 length=x['length'],
									 path=x['path'],
									 manufacturer=x['manufacturer'],
									 movieName=x['movieName'],
									 ReCommandTime=datetime.now().date(),
									 email=current_user.email)
				reObject.save()
				result.append(x)
	except KeyError:
		session['reDate'] = reDateStr
		count = mongo.db.mov.count()
		result = list()
		for _ in xrange(3):
			x = mongo.db.mov.find()[random.randrange(count)]
			reObject = ReCommand(code=x['code'],
								 postTime=x['postTime'],
								 publisher=x['publisher'],
								 type=x['type'],
								 actress=x['actress'],
								 director=x['director'],
								 length=x['length'],
								 path=x['path'],
								 manufacturer=x['manufacturer'],
								 movieName=x['movieName'],
								 ReCommandTime=datetime.now().date(),
								 email=current_user.email)
			reObject.save()
			result.append(x)
	finally:
		flash("Recommended three films a day",category='info')
		return render_template('lucky.html',data=result,day=reDateStr)


@avbd_app.route('/actress/<name>')
@login_required
def show(name):
	image =''
	data = mongo.db.mov.find({"actress":name}).count()
	sel = mongo.db.act.find({"actressName": name})
	for i in sel:
		try:
			image =  i['files'][0]['path']
		except:
			image = "act/x.jpg"
	return render_template('act.html',name=name,key="actress",data=data,image=image)


@avbd_app.route('/type/<name>')
@login_required
def type(name):
	data = mongo.db.mov.find({"type": name}).count()
	return render_template('act.html',name=name,key="type",data=data)


@avbd_app.route('/movie')
@login_required
def movie():
	data = mongo.db.mov.count()
	return render_template('act.html',data=data)


@avbd_app.route('/mov_data/<key>/<name>')
@login_required
def get_mov_data(key,name):
	columns = ['PostTime', 'Code', 'Name', 'Publisher', 'Director', 'Manufacture', 'Length', 'Type','Actress']
	index_column = "_id"
	collection = "mov"
	results = DataTablesServer(request, columns, index_column, collection,key,name).mov_result()
	return json.dumps(results)


@avbd_app.route('/about')
@login_required
def about():
	return render_template("about.html")



order_dict = {'asc': 1, 'desc': -1}

class DataTablesServer(object):
	def __init__(self, request, columns, index, collection,key,name):
		self.columns = columns
		self.index = index
		self.collection = collection
		self.request_values = request.values
		self.name = name
		self.result_data = None
		self.cardinality_filtered = 0
		self.cardinality = 0
		self.key = key
		self.run_queries()
	def mov_result(self):
		output = {}
		output['sEcho'] = str(int(self.request_values['sEcho']))
		output['iTotalRecords'] = str(self.cardinality)
		output['iTotalDisplayRecords'] = str(self.cardinality_filtered)
		aaData_rows = []
		for row in self.result_data:
			data = {}
			data['PostTime'] = row['postTime']
			data['Code'] = row.get('code')
			data['Publisher'] = row.get('publisher')
			data['Type'] = row.get('type')
			data['Director'] = row.get('director')
			data['Length'] = row.get('length')
			data['Name'] = row.get('movieName')
			data['Actress'] = row.get('actress')
			data['Manufacturer'] = row.get('manufacturer')
			data['height'] = row.get('Height')
			aaData_rows.append(data)
		output['aaData'] = aaData_rows
		return output

	def act_result(self):

		output = {}
		output['sEcho'] = str(int(self.request_values['sEcho']))
		output['iTotalRecords'] = str(self.cardinality)
		output['iTotalDisplayRecords'] = str(self.cardinality_filtered)
		aaData_rows = []
		for row in self.result_data:
			data = {}
			data['actressName'] = row['actressName']
			data['cup'] = row.get('Cup')
			data['age'] = row.get('Age')
			data['waist'] = row.get('Waist')
			data['bust'] = row.get('Bust')
			data['birthday'] = row.get('Birthday')
			data['hips'] = row.get('Hips')
			data['hobby'] = row.get('Hobby')
			data['hometown'] = row.get('Hometown')
			data['height'] = row.get('Height')
			for  i in row['files']:
				data['path'] = i.get('path')
			aaData_rows.append(data)
		output['aaData'] = aaData_rows
		return output





	def run_queries(self):
		pages = self.paging()
		_filter = self.filtering()
		sorting = self.sorting()
		if self.name == "all":
			self.result_data = list(mongo.db[self.collection].find(filter=_filter,
															   skip=pages.start,
															   limit=pages.length,
															   sort=sorting).sort("postTime",pymongo.DESCENDING))

			self.cardinality_filtered = mongo.db[self.collection].find(filter=_filter).count()
			self.cardinality = mongo.db[self.collection].find().count()
		else:
			self.result_data = list(mongo.db[self.collection].find({self.key:self.name},limit=pages.length,
																	skip=pages.start,
																	sort=sorting
																   ).sort("postTime",pymongo.DESCENDING))
			self.cardinality_filtered = mongo.db[self.collection].find({self.key:self.name}).count()
			self.cardinality = mongo.db[self.collection].find({self.key:self.name}).count()


	def filtering(self):
		_filter = {}
		if (self.request_values.has_key('sSearch')) and (self.request_values['sSearch'] != ""):
			or_filter_on_all_columns = []
			for i in range(len(self.columns)):
				column_filter = {}
				column_filter[self.columns[i]] = {'$regex': self.request_values['sSearch'], '$options': 'i'}
				or_filter_on_all_columns.append(column_filter)
			_filter['$or'] = or_filter_on_all_columns
		return _filter

	def sorting(self):
		order = []
		if (self.request_values['iSortCol_0'] != "") and (self.request_values['iSortingCols'] > 0):
			for i in range(int(self.request_values['iSortingCols'])):
				column_number = int(self.request_values['iSortCol_' + str(i)])
				sort_direction = self.request_values['sSortDir_' + str(i)]
				order.append((self.columns[column_number], order_dict[sort_direction]))
		return order

	def paging(self):

		pages = namedtuple('pages', ['start', 'length'])
		if (self.request_values['iDisplayStart'] != "") and (self.request_values['iDisplayLength'] != -1):
			pages.start = int(self.request_values['iDisplayStart'])
			pages.length = int(self.request_values['iDisplayLength'])
		return pages




